<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Works extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Album_model');
        $this->load->model('Photo_model');
    }

    public function index()
    {
        // $id = _get_key_val($this->input->get('id'),true);
        // $o = $this->Order_model->get_info_by_id($id);
        // $result = array(
        // 'o' => $o,
        // );
        $agid = _get_key_val($this->input->get('agid'), true);
        if (! $agid)
            $agid = $this->thatUser['id'];
        $page = _get_page();
        $pagesize = 9;
        $arrParam = array();
        $arrWhere = array(
            'userid' => $agid,
            'status<>' => - 1
        );
        
        $list = $this->Album_model->get_list($arrWhere);
        $photo_list = array();
        if ($list)
        {
        	$photo_type = array();
        	foreach ($list as $key=>$val)
        	{
        		if ($val['title'] != '精选作品')
        		{
        			if (!in_array($val['type'], $photo_type))
        			{
        				array_push($photo_type, $val['type']);
        				$photo_list[$val['type']] = array();
        			}
        			array_push($photo_list[$val['type']], $val);
        		}
        		else
        		{
        			$photo_list[0] = array();
        			array_unshift($photo_list[0], $val);
        		}
        	}
        	ksort($photo_list);
        }
//         $list = $this->Album_model->fetch_page($page, $pagesize, $arrWhere);
        // echo $this->db->last_query();die;
        
        $this->load->model('User_model');
        $user = $this->User_model->get_by_id($agid,'usertype');
        
        // 分页
//         $pagecfg = array();
//         $pagecfg['base_url'] = _create_url('m/works', $arrParam);
//         $pagecfg['total_rows'] = $list['count'];
//         $pagecfg['cur_page'] = $page;
//         $pagecfg['per_page'] = $pagesize;
//         $this->pagination->initialize($pagecfg);
//         $list['pages'] = $this->pagination->create_links();
        
        //相册分类
        $photo_type = _get_config('photo_type');
        $photoArr = $photo_type[6];
        if (in_array($user['usertype'], array(1,2)))
        {
        	$photoArr = $photo_type[$user['usertype']];
        }
        
        $result = array(
            'list' => $photo_list,
            'agid' => $agid,
        	'photoArr' => $photoArr
        );
        
        $this->load->view('m/works', $result);
    }

    /*
     * public function photoList($albumid){
     *
     * $userid = $this->thatUser['id'];
     *
     * $arrWhere = array('userid'=>$userid,'albumid'=>$albumid,'status'=>1);
     *
     * $photolist = $this->Photo_model->get_list($arrWhere,'id,img,title');
     *
     * $data = array(
     * 'photolist' => $photolist,
     * );
     *
     * $this->load->view('m/photolist', $data);
     *
     * }
     */
    public function addalbum()
    {
        $msg = '操作失败！';
        $url = '/m/works';
        
        if ($this->input->is_post())
        {
            // 验证规则
            $config = array(
//                 array(
//                     'field' => 'title',
//                     'label' => '相册名称',
//                     'rules' => 'trim|required'
//                 ),
                array(
                    'field' => 'memo',
                    'label' => '相册描述',
                    'rules' => 'trim|required'
                )
            );
            
            $this->form_validation->set_rules($config);
            
            if ($this->form_validation->run() === TRUE)
            {
                $msg = '添加成功';
                $id = _get_key_val($this->input->post('albumid'), TRUE);
                $agid = _get_key_val($this->input->post('agid'), TRUE);
                
                // 处理昵称
                if ($agid)
                {
                    $agUser = $this->User_model->fetch_row(array(
                        'id' => $agid
                    ), 'nickname');
                    if ($agUser)
                    {
                        $agnickname = $agUser['nickname'];
                    }
                    $url .= '?agid=' . $this->input->post('agid');
                } else
                {
                    $agid = $this->thatUser['id'];
                    $agnickname = $this->thatUser['nickname'];
                }
                
                // 上传封面图
                $cover = $this->uploadCover('cover');
                
                $title = $this->input->post('title');
                $title = isset($title)?$title:'精选作品';
                if ($id)
                {
                    $msg = '修改成功';
                    $data = array(
                        'title' => $title,
                        'memo' => $this->input->post('memo'),
//                         'showimg' => $cover,
                        'updatetime' => time(),
                        'op_userid' => $this->loginID,
                        'op_nickname' => $this->loginNickName,
                    	'type' => $this->input->post('type'),
                        'op_time' => time()
                    );
                    if ($cover)
                    {
                        $data['showimg'] = $cover;
                    }
//                     $data['id'] = $id;
                    
                    $this->Album_model->update_by_id($id,$data);
                } 
                else
                {
                    $data = array(
                        'userid' => $agid,
                        'nickname' => $agnickname,
                        'insid' => $this->loginInsID,
                        'title' => $title,
                        'memo' => $this->input->post('memo'),
                    	'type' => $this->input->post('type'),
                        'showimg' => $cover,
                        'addtime' => time(),
                        'status' => 1,
                        'op_userid' => $this->loginID,
                        'op_nickname' => $this->loginNickName,
                        'op_time' => time()
                    );
                    
                    $this->Album_model->insert($data);
                }
            } else
            {
                $error_messages = $this->form_validation->getErrors();
            }
            
            if (isset($error_messages) && is_array($error_messages))
            {
                foreach ($error_messages as $e)
                {
                    $msg .= $e . '\n';
                }
            }
        } // -is_post()
        
        $url = "/m/works";
        if ($agid)
        {
        	$url = '/m/works?agid='._get_key_val($agid);
        }
        redirect($url);
//         alert($msg, $url);
//         exit();
    }

    public function album()
    {
        $res = array(
            'code' => 0,
            'data' => array()
        );
        $id = _get_key_val($this->input->get('id'), TRUE);
        $o = $this->Album_model->get_info_by_id($id, 'title,memo,type,kind');
        $res['code'] = 200;
        $res['data'] = $o;
        
        $this->view->json($res);
        exit();
    }

    public function delalbum()
    {
        $res = array(
            'code' => 0,
            'data' => array()
        );
        $id = _get_key_val($this->input->post('id'), TRUE);
        
        $userid = _get_key_val($this->input->post('userid'), TRUE);
        
        $this->Album_model->update_by_where(array(
            'id' => $id
        ), array(
            'status' => - 1
        ));
        $this->load->service('num_service');
        $this->num_service->set_album_photo_num($userid, 'photonum', $id);
        $res['code'] = 200;
        
        $this->view->json($res);
    }

    public function photo($albumid = 0)
    {
        $agid = _get_key_val($this->input->get('agid'), TRUE);
        
        if (! $agid)
        {
            $agid = $this->thatUser['id'];
        }
        
        $id = _get_key_val($this->input->get('id'), TRUE);
        
        $arrListWhere = array(
            'userid' => $agid,
            'status' => 1
        );
        $list = $this->Album_model->get_list($arrListWhere, 'id,title', 'addtime desc');
        
        if (! empty($list) && empty($albumid))
        {
            $albumId = $list[0]['id'];
        }
        
        if (! empty($albumid))
        {
            $albumId = $albumid;
        }
        
        $arrWhere = array(
            'userid' => $agid,
            'albumid' => $albumId,
            'status' => 1
        );
        $photolist = $this->Photo_model->get_list($arrWhere, 'id,img,title', 'addtime desc');
        
        $result = array(
            'albumlist' => $list,
            'photolist' => empty($photolist) ? 0 : $photolist,
            'albumid' => empty($albumid) ? 0 : $albumid,
            'agid' => $agid
        );
        
        $this->load->view('m/worksphoto', $result);
    }

    public function delphoto()
    {
        $res = array(
            'code' => 0,
            'data' => array()
        );
        $id = _get_key_val($this->input->post('id'), TRUE, FALSE);
        $userid = $this->input->post('user_id');
        if (! $id)
        {
            $id = $this->input->post('id');
        }
        if ($id)
        {
            $aPhoto = $this->Photo_model->get_by_id($id);
            if ($aPhoto)
            {
                $albumid = $aPhoto['albumid'];
                $this->Photo_model->update_by_where(array(
                    'id' => $id,
                    'userid' => $userid
                ), array(
                    'status' => 0
                ));
                $this->load->service('num_service');
                
                if ($albumid)
                {
                    // 获取相册中的最新相片信息
                    $this->load->model('Album_model');
                    $albumInfo = $this->Album_model->get_by_id($albumid);
                    
                    $this->num_service->set_album_photo_num($userid, 'photonum', $albumid);
                }
                
//                 if (! empty($albumInfo) && (1 == $albumInfo['kind']))
				if ($albumInfo && !$albumInfo['showimg'])
                {
                    // 系统默认设置新的封面
                    $photoList = $this->Photo_model->get_list(array(
                        'albumid' => $albumid,
                        'userid' => $userid,
                        'status' => 1
                    ), '*', 'addtime desc', 1);
                    if (! empty($photoList))
                    {
                        $this->Album_model->update_by_where(array(
                            'id' => $albumid
                        ), array(
                            'showimg' => $photoList[0]['img']
                        ));
                    }
                }
                
                $res['code'] = 200;
            } else
            {
                $res['code'] = 201;
            }
        }
        
        $this->view->json($res);
    }

    public function getphoto()
    {
        $res = array(
            'code' => 0,
            'data' => array()
        );
        $id = _get_key_val($this->input->post('albumid'), TRUE);
        $arrWhere = array(
            'albumid' => $id,
            'status' => 1
        ); // 'userid'=>$this->thatUser['id']
        
        $photolist = $this->Photo_model->get_list($arrWhere, 'id,img,title', 'addtime desc');
        $res['code'] = 200;
        $res['data']['photolist'] = $photolist;
        
        $this->view->json($res);
    }

    /**
     * 上传封面图
     */
    private function uploadCover($str)
    {
        $path = "./upload/photo/" . date('Ym', time()) . '/';
        mkpath($path); // 没有就创建
        $pic_config['upload_path'] = $path;
        $pic_config['allowed_types'] = 'gif|jpg|png';
        $pic_config['file_name'] = 'photo_' . $this->loginID . '_' . time() . '.jpg'; // 重新命名
        
        $this->load->library('upload', $pic_config);
        if (! $this->upload->do_upload($str))
        {
            $error[] = $this->upload->display_errors();
            return '';
        }
        
        // 图片处理
        $img_data = $this->upload->data();
        // 1. 缩小
//         $pic_config['image_library'] = 'gd2';
//         $pic_config['source_image'] = $img_data['full_path'];
//         $pic_config['maintain_ratio'] = TRUE;
//         $pic_config['width'] = 260; // 缩小处理
//         $pic_config['height'] = 256; // 头像框中最大高度的像素
//         $this->load->library('image_lib', $pic_config);
//         if (! $this->image_lib->resize())
//         {
//             $error[] = $this->image_lib->display_errors();
//         }
        
        //2. 裁剪
        //宽度比例
        if ($this->input->post('width') > $this->input->post('rel_width'))
        {
        	$rate_width = $this->input->post('width')/$this->input->post('rel_width');
        }
        else
        {
        	$rate_width = $this->input->post('rel_width')/$this->input->post('width');
        }
        //高度比例
        if ($this->input->post('height') > $this->input->post('rel_height'))
        {
        	$rate_height = $this->input->post('height')/$this->input->post('rel_height');
        }
        else
        {
        	$rate_height = $this->input->post('rel_height')/$this->input->post('height');
        }
        //2. 裁剪
        $img_config['source_image'] = $img_data['full_path']; //全路径
        $img_config['x_axis'] = $this->input->post('left')*$rate_width;
        $img_config['y_axis'] = $this->input->post('top')*$rate_height;
        $img_config['width'] = ($this->input->post('right') - $this->input->post('left'))*$rate_width; //宽度
        $img_config['height'] = ($this->input->post('bottom') - $this->input->post('top'))*$rate_height; //高度
        $img_config['maintain_ratio'] =  false;
         
        //     		$this->image_lib->initialize($img_config);
        $this->load->library('image_lib', $img_config);
        if (!$this->image_lib->crop())
        {
        	$error[] =  $this->image_lib->display_errors();
        }
        
        //裁剪后上传OSS
        $this->upload->cropUpload();
        
//         $img_config['source_image'] = $img_data['full_path']; //全路径
//         $this->input->post('left'); 
//         $img_config['y_axis'] = $this->input->post('top'); 
//         $img_config['width'] = $this->input->post('right') - $this->input->post('left'); //宽度
//         $img_config['height'] = $this->input->post('bottom') - $this->input->post('top'); //高度
//         $img_config['maintain_ratio'] =  false;
//         $this->image_lib->initialize($img_config);
//         if (!$this->image_lib->crop())
//         {
//             $error[] =  $this->image_lib->display_errors();
//         }
        
        $fileName = $path . $pic_config['file_name'];
        
        return $fileName;
    }
}